package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-07-21 9:25
 */
@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
@Slf4j
public class SupplyTask implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //1.解析json数据
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);

        //2.innercode 货道数据 协议数据 -> taskViewModel
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setAssignorId(0);
        taskViewModel.setDesc(jsonMsg);
        taskViewModel.setCreateType(VMSystem.VM_CREATE_TYPE_AUTO);
        taskViewModel.setInnerCode(supplyContract.getInnerCode());
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);

        Integer leastUser = taskService.getLeastUser(supplyContract.getRegionId(), false);
        if(leastUser == null){
            //区域内没有人
            log.info("补货工单区域内无人处理:区域id{}",supplyContract.getRegionId());
            return;
        }
        taskViewModel.setUserId(leastUser);

        List<TaskDetailsViewModel> taskDetailsViewModels = new ArrayList<>();
        taskViewModel.setDetails(taskDetailsViewModels);

        List<SupplyChannel> supplyData = supplyContract.getSupplyData();
        for (SupplyChannel supplyDatum : supplyData) {
            TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
            taskDetailsViewModel.setSkuId(supplyDatum.getSkuId());
            taskDetailsViewModel.setSkuImage(supplyDatum.getSkuImage());
            taskDetailsViewModel.setChannelCode(supplyDatum.getChannelId());
            taskDetailsViewModel.setExpectCapacity(supplyDatum.getCapacity());
            taskDetailsViewModel.setSkuName(supplyDatum.getSkuName());
            taskDetailsViewModels.add(taskDetailsViewModel);
        }
        //3.调用service create方法
        taskService.create(taskViewModel);
    }

}
